/**
 * 
 */
package cn.nzp.core.openapi.server.si.common;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;

import com.alibaba.dubbo.rpc.protocol.rest.RestConstraintViolation;
import com.alibaba.dubbo.rpc.protocol.rest.RpcExceptionMapper;
import com.alibaba.dubbo.rpc.protocol.rest.ViolationReport;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;

/**
 *  @author xiejindun
 *	添加自定义的ExceptionMapper来自由的定制错误返回格式, 这里改为返回json格式
 *	最简单的方式是直接继承dubbo rest的RpcExceptionMapper，并覆盖其中处理校验异常的方法即可
 *	然后配置到 dubbo:protocol的extension节点
 */
public class MyValidationExceptionMapper extends RpcExceptionMapper {

	@SuppressWarnings("rawtypes")
	protected Response handleConstraintViolationException(ConstraintViolationException cve) {
		ViolationReport report = new ViolationReport();
		for (ConstraintViolation cv : cve.getConstraintViolations()) {
			report.addConstraintViolation(
					new RestConstraintViolation(
							cv.getPropertyPath().toString(), 
							cv.getMessage(), 
							cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString()));
		}
		
		// 采用json输出代替xml输出
		return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.APPLICATION_JSON_UTF_8).build();
		
		// 返回举例：
		// {"constraintViolations":[{"path":"demoTestArgument0","message":"User ID must be greater than 1","value":"0"}]}
	}
}
